// package-star/pages/manage-target-exchange/index.js
import { TARGET_TYPE } from '../../../constants/common';
import { TAB_BAR_PAGE, PACKAGE_STAR_PAGE } from '../../../constants/route';
import { ManageTargetInfoUpdateMixins } from '../../../behaviors/page';
import { reLaunchTo, navTo, showLoading, hideLoading } from '../../../common/env';
import { setMangeTargetId } from '../../../biztools/wex';
import { getBrandList, getPreBrandList } from '../../../api/brd';
import { getStoreList, getPreStoreList } from '../../../api/sto';
let loaded = false;

Page({
    mixins: [ManageTargetInfoUpdateMixins],
    data: {
        TARGET_TYPE,
        tab: TARGET_TYPE.brand,
        tabs: [
            { value: TARGET_TYPE.brand, name: '品牌主页' },
            { value: TARGET_TYPE.store, name: '店铺主页' },
        ],
        exchangeList: [],
        preOpenCount: 0,
    },
    onLoad(options) {
        const { tab } = options;
        this.setData({ tab }, async () => {
            await this._handleGetList();
        });
    },
    async _handleGetList() {
        !loaded && showLoading('加载中...');
        const { tab = TARGET_TYPE.brand } = this.data;
        let exchangeList = [], preOpenList = [];
        if (tab === TARGET_TYPE.brand) {
            exchangeList = await getBrandList();
            preOpenList = await getPreBrandList();
        } else if (tab === TARGET_TYPE.store) {
            exchangeList = await getStoreList();
            preOpenList = await getPreStoreList();
        }
        this.setData({
            exchangeList,
            preOpenCount: preOpenList.length,
        });
        if (!loaded) hideLoading(); loaded = true;
    },
    handleTabChange(e) {
        const { name } = e.detail;
        this.setData({ tab: name }, () => {
            this._handleGetList();
        });
    },
    handleExchange(e) {
        const { tab } = this.data;
        const { storeId, brandId } = e.detail;
        setMangeTargetId(tab, tab === TARGET_TYPE.brand ? brandId : storeId);
        reLaunchTo(TAB_BAR_PAGE['star']);
    },
    handleNavToEditBrand() {
        navTo(PACKAGE_STAR_PAGE.brandOpen);
    },
    handleNavToManageTargetOpen() {
        const { tab } = this.data;
        navTo(PACKAGE_STAR_PAGE.manageTargetOpen, {
            tab,
        });
    },
})
